package com.feng.security.dsa;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

public class SignatureHelper {
	public SignatureHelper() {
	}

	/**
	 * 将Properties中属性依据升序进行排序,并以标准URL参数格式输出(&分割),Properties中的sign与sign_type不包含在内
	 * 
	 * @param properties
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getSignatureContent(Properties properties) {
		StringBuffer content = new StringBuffer();
		List keys = new ArrayList((Collection) properties.keySet());
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			if (key == null || key.equalsIgnoreCase("sign")
					|| key.equalsIgnoreCase("sign_type")) {
				continue;
			}
			String value = properties.getProperty(key);
			content
					.append((new StringBuilder(String
							.valueOf(i != 0 ? "&" : ""))).append(key).append(
							"=").append(value).toString());
		}
		return content.toString();
	}
	
	/**
	 * 将Properties中属性依次以标准URL参数格式输出(&分割),Properties中的sign与sign_type不包含在内
	 * 
	 * @param properties
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getSignatureContentAms(Properties properties) {
		StringBuffer content = new StringBuffer();
		List keys = new ArrayList((Collection) properties.keySet());
		//Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			if (key == null || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) {
				continue;
			}
			String value = properties.getProperty(key);
			content.append((new StringBuilder(String
							.valueOf(i != 0 ? "&" : ""))).append(key).append(
							"=").append(value).toString());
		}
		return content.toString();
	}

	/**
	 * 从request中获取parameter的properties，其中包括sign及sign_type
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Properties getPropertiesFromRequest(HttpServletRequest request,
			String charset) {
		Properties properties = new Properties();
		Map params = null;
		try {
			if (request == null) {
				return properties;
			}
			params = request.getParameterMap();
			for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String value = URLDecoder.decode(((String[])params.get(name))[0],
						charset);
				properties.setProperty(name, value.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return properties;
	}

	/**
	 * 从Request QueryString中获取parameter的properties，其中包括sign及sign_type
	 * 
	 * @param queryString
	 * @param charset
	 * @return
	 */
	public Properties getPropertiesFromQueryString(String queryString,
			String charset) {
		Properties properties = null;
		try {
			if (queryString == null) {
				return null;
			}
			if (charset == null)
				charset = "GBK";
			String splitStrArray[] = queryString.split("&");
			properties = new Properties();

			for (int i = 0; i < splitStrArray.length; i++) {
				String param[] = splitStrArray[i].split("=");
				String name = param[0];
				String value = param[1];
				properties.setProperty(name, URLDecoder.decode(value, charset));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return properties;
	}

	/**
	 * 生成请求URL参数，参数值中的特殊符号进行转义
	 * 
	 * @param properties
	 * @param charset
	 * @return
	 */
	public String genSignURL(Properties properties, String charset) {
		StringBuffer buffer = new StringBuffer();
		if (charset == null || charset.length() == 0)
			charset = "GBK";
		try {
			Enumeration<Object> enumeration = properties.keys();
			for (int mark = 0; enumeration.hasMoreElements(); mark++) {
				String name = (String) enumeration.nextElement();
				String keyValue = (new StringBuilder(String.valueOf(name)))
						.append("=").append(
								URLEncoder.encode(properties.getProperty(name),
										charset)).toString();// 对参数值进行编码，值中的特殊字符进行转义
				if (mark < properties.size() - 1)
					buffer.append((new StringBuilder(String.valueOf(keyValue)))
							.append("&").toString());
				else
					buffer.append(keyValue);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * 将字符串转行为指定字符集的byte[]
	 * 
	 * @param content
	 * @param charset
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public byte[] getContentBytes(String content, String charset)
			throws UnsupportedEncodingException {
		if (charset == null || charset.length() == 0)
			return content.getBytes();
		else
			return content.getBytes(charset);
	}
}
